<template>
  <page-header-wrapper :title="false">
    <a-card :bordered="false" :style="{margin:'0 -24px',padding:0}">
      <div class="table-operator">
        <a-button type="primary" icon="plus" @click="handleAdd" v-action:question_add>新建</a-button>
      </div>

      <s-table
        ref="table"
        size="default"
        rowKey="id"
        :columns="columns"
        :data="loadData"
        showPagination="auto"
      >
        <span slot="question_description" slot-scope="text, record, index">
          <div>{{ index + 1 }}. {{ record.question_description }}: </div>
          <div>
            <a-checkbox v-for="(item, i) in JSON.parse(record.question_option)" :key="i" v-model="item.is_right_answer">{{ item.option }}</a-checkbox>
          </div>
        </span>
        <span slot="status" slot-scope="text">
          <a-badge :status="text | statusTypeFilter" :text="text | statusFilter" />
        </span>
        <span slot="action" slot-scope="text, record">
          <template>
            <a @click="handleChangeStatus(record, record.status == 2 ? 1 : 2)" v-action:question_edit>{{ record.status == 2 ? '启用' : '停用' }}</a>
            <a-divider type="vertical" v-action:question_edit/>
            <a @click="handleEdit(record)" v-action:question_edit>编辑</a>
            <a-divider type="vertical" v-action:question_del/>
            <a @click="handleChangeStatus(record, 3)" v-action:question_del>删除</a>
          </template>
        </span>
      </s-table>
      <!-- 增/查/改 弹出模板 -->
      <create-form
        ref="createModal"
        :visible="visible"
        :loading="confirmLoading"
        :model="mdl"
        @cancel="handleCancel"
        @ok="handleOk"
        :okHidden="okHidden"
      />
      <!-- 删除/停用确认窗 -->
      <a-modal
        title="提示"
        :visible="modal.show"
        :confirm-loading="modal.loading"
        @ok="modal.confirm"
        @cancel="modal.show = false"
      >
        <p>{{ modal.text }}</p>
      </a-modal>
      <!-- <step-by-step-modal ref="modal" @ok="handleOk"/> -->
    </a-card>
  </page-header-wrapper>
</template>

<script>
import { STable } from '@/components'
import CreateForm from './modules/CreateQuestionBankForm'
import { questionList, questionDel, questionEdit, questionAdd } from '@/api/exam'

const columns = [
  {
    title: 'id',
    dataIndex: 'id',
    align: 'center'
  },
  {
    title: '题目',
    dataIndex: 'question_description',
    align: 'center',
    scopedSlots: { customRender: 'question_description' }
  },
  {
    title: '状态',
    dataIndex: 'status',
    align: 'center',
    scopedSlots: { customRender: 'status' }
  },
  {
    title: '操作',
    dataIndex: 'action',
    width: '300px',
    align: 'center',
    scopedSlots: { customRender: 'action' }
  }
]
const statusMap = {
  2: {
    status: 'default',
    text: '停用'
  },
  1: {
    status: 'success',
    text: '启用'
  }
}
export default {
  components: {
    STable,
    CreateForm
  },
  data () {
    this.columns = columns
    return {
      // create model
      visible: false,
      confirmLoading: false,
      okHidden: false,
      mdl: {
        survey_id: '',
        question_description: '',
        score: '',
        question_option: [],
        right_answer: ''
      },
      // 高级搜索 展开/关闭
      advanced: false,
      // 查询参数
      queryParam: {},
      isPost: false,
      // 加载数据方法 必须为 Promise 对象
      loadData: async parameter => {
        if (!this.isPost) return
        const params = {
          page: parameter.pageNo,
          per_page: parameter.pageSize
        }
        const res = await questionList({
          ...params,
          ...this.queryParam
        })
        const result = {
          pageNo: res.current_page,
          totalPage: res.last_page,
          data: res.data,
          pageSize: 10,
          totalCount: res.total
        }
        return Promise.resolve(result)
      },
      modal: {
        show: false,
        text: '',
        loading: false,
        confirm: () => {},
        cancel: () => {}
      },
      selectedRowKeys: [],
      selectedRows: []
    }
  },
  computed: {
    rowSelection () {
      return {
        selectedRowKeys: this.selectedRowKeys,
        onChange: this.onSelectChange
      }
    }
  },
  filters: {
    statusFilter (type) {
      return statusMap[type].text
    },
    statusTypeFilter (type) {
      return statusMap[type].status
    }
  },
  created () {
    // console.log(this.$router.app._route.query)
    this.queryParam['survey_id'] = this.$router.app._route.query.id
    this.mdl['survey_id'] = this.$router.app._route.query.id
    this.isPost = true
    this.$nextTick(() => {
      this.$refs.table.refresh()
    })
    // sortList().then(res => {
    //   console.log(res.list)
    //   this.sortList = res.list
    // }).catch(err => {
    //   console.log('错误', err)
    // })
  },
  methods: {
    handleAdd () {
      this.mdl = null
      this.mdl = {
        survey_id: this.queryParam['survey_id'],
        question_description: '',
        score: '',
        question_option: [{
          'option': '',
          'is_right_answer': false,
          'sort': 1
        }],
        right_answer: ''
      }
      this.visible = true
    },
    handleEdit (record) {
      const reg = /\\/g
      const replaceAfter = record.question_option.replace(reg, '')
      record.question_option = replaceAfter
      this.mdl = { ...record, ...{ survey_id: this.queryParam['survey_id'] } }

      this.visible = true
      // console.log()
    },
    handleOk () {
      const form = this.$refs.createModal.form
      this.confirmLoading = true
      form.validateFields((errors, values) => {
        if (!errors) {
          const success = (res, info) => {
            if (res.is_ok === 'Y') {
              this.handleVisible()
              form.resetFields()
              this.$refs.table.refresh()
              this.$message.info(info)
            }
          }
          const final = () => { this.confirmLoading = false }
          if (values.id > 0) {
            console.log(values)
            questionEdit(values)
              .then(res => success(res, '修改成功'))
              .finally(final)
          } else {
            // values.question_option = JSON.parse(values.question_option)
            questionAdd(values)
              .then(res => success(res, '新增成功'))
              .finally(final)
          }
        } else {
          this.confirmLoading = false
        }
      })
    },
    handleChangeStatus (record, type) {
      this.openModal(questionDel, record, type === 1 ? '启用' : type === 2 ? '停用' : '删除')
    },
    openModal (method, record, statusText) {
      this.modal = {
        ...this.modal,
        text: `确定${ statusText }该分类吗？`,
        show: true,
        confirm: async () => {
          try {
            this.modal.loading = true
            if (statusText == '启用') {
              const res = await method({ id: record.id, status: 1 })
              if (res.is_ok === 'Y') {
                this.modal.loading = false
                this.modal.show = false
                this.$refs.table.refresh()
                this.$message.info(`${ statusText }成功`)
              }
            } else if (statusText == '停用') {
              const res = await method({ id: record.id, status: 2 })
              if (res.is_ok === 'Y') {
                this.modal.loading = false
                this.modal.show = false
                this.$refs.table.refresh()
                this.$message.info(`${ statusText }成功`)
              }
            } else if (statusText == '删除') {
              const res = await method({ id: record.id, status: 3 })
              if (res.is_ok === 'Y') {
                this.modal.loading = false
                this.modal.show = false
                this.$refs.table.refresh()
                this.$message.info(`${ statusText }成功`)
              }
            } else {
              const res = await method({ id: record.id, status: 3 })
              if (res.is_ok === 'Y') {
                this.modal.loading = false
                this.modal.show = false
                this.$refs.table.refresh()
                this.$message.info(`${ statusText }成功`)
              }
            }
          } catch (err) {
            console.warn(err)
            this.modal.loading = false
          }
        }
      }
    },
    handleCancel () {
      this.handleVisible()
      const form = this.$refs.createModal.form
      form.resetFields() // 清理表单数据（可不做）
    },
    handleVisible () {
      // this.mdl = null
      this.visible = false
      setTimeout(() => {
        this.okHidden = false
      }, 350)
    },
    onSelectChange (selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    },
    toggleAdvanced () {
      this.advanced = !this.advanced
    },
    resetSearchForm () {
      this.queryParam = {}
    }
  }
}
</script>
